using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

using MyFirstGame.Objects;

namespace MyFirstGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;

        // This is a texture we can render.
        private Texture2D txtBackground;
        private Texture2D[] txtBullets;
        private Rectangle visibleCanvas;

        // Set the coordinates to draw the sprite at.
        private Vector2 spritePosition = new Vector2(0,0);

        // Store some information about the sprite's motion.
        private float speedFactor;

        // Store information about the current scenario.
        private int currentScenario;

        private SpaceCraft spaceCraft;
        private List<Bullet> bullets;

        private KeyboardState oldKeyState;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            this.speedFactor = 5f;
            this.currentScenario = 1;

            this.visibleCanvas = new Rectangle(0, 0, this.graphics.GraphicsDevice.Viewport.Width, this.graphics.GraphicsDevice.Viewport.Height);

            // Init player's space craft.
            this.spaceCraft = new SpaceCraft(this.graphics);
            this.spaceCraft.Position = new Vector2(0, (graphics.GraphicsDevice.Viewport.Height / 2));

            // Init objects
            this.bullets = new List<Bullet>();

            oldKeyState = Keyboard.GetState();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            this.spaceCraft.Texture = Content.Load<Texture2D>("fireball");
            this.txtBackground = Content.Load<Texture2D>("background1");

            this.txtBullets = new Texture2D[6];
            this.txtBullets[0] = Content.Load<Texture2D>("bullet_explosion_1");
            this.txtBullets[1] = Content.Load<Texture2D>("bullet_explosion_2");
            this.txtBullets[2] = Content.Load<Texture2D>("bullet_explosion_3");
            this.txtBullets[3] = Content.Load<Texture2D>("bullet_explosion_4");
            this.txtBullets[4] = Content.Load<Texture2D>("bullet_explosion_5");
            this.txtBullets[5] = Content.Load<Texture2D>("bullet_explosion_6");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
                this.Exit();

            UpdateInput();

            // TODO: Add your update logic here
            foreach (Bullet bullet in this.bullets)
            {
                if (bullet.Status == BulletStatus.Moving)
                {
                    bullet.UpdateBulletPosition();
                    
                    if (bullet.Position.X >= 500)
                    {
                        bullet.ChangeBulletStatus(BulletStatus.Hit);
                    }
                }
            }

            base.Update(gameTime);
        }

        public void UpdateInput()
        {
            KeyboardState newKeyState = Keyboard.GetState();

            // Keyboard keys
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Left))
                this.MoveBackward();
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up))
                this.MoveUp();
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Down))
                this.MoveDown();
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Right))
                this.MoveForward();

            // Is the SPACE key down?
            if (newKeyState.IsKeyDown(Keys.Space))
            {
                // If not down last update, key has just been pressed.
                if (!oldKeyState.IsKeyDown(Keys.Space))
                {
                    this.Fire();
                }
            }
            else if (oldKeyState.IsKeyDown(Keys.Space))
            {
                // Key was down last update, but not down now, so
                // it has just been released.
            }

            // Update saved state.
            oldKeyState = newKeyState;
        }

        #region User Events
        private void MoveBackward()
        {
            this.spaceCraft.UpdatePosition(-this.speedFactor, 0);
        }
        private void MoveUp()
        {
            this.spaceCraft.UpdatePosition(0, -this.speedFactor);
        }
        private void MoveDown()
        {
            this.spaceCraft.UpdatePosition(0, this.speedFactor);
        }
        private void MoveForward()
        {
            this.spaceCraft.UpdatePosition(this.speedFactor, 0);
        }
        private void Fire()
        {
            this.bullets.Add(new Bullet(this.spaceCraft.CenterPosition, Direction.Right, this.speedFactor, 10, this.txtBullets));
        }        
        #endregion

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
            spriteBatch.Draw(this.txtBackground, this.visibleCanvas, Color.White);

            foreach (Bullet bullet in this.bullets)
            {
                spriteBatch.Draw(bullet.CurrentTexture, bullet.Position, Color.White);
            }

            spriteBatch.Draw(this.spaceCraft.Texture, this.spaceCraft.Position, Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
